//
//  SINAStuApproveUserNameViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/26.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINAStuApproveSchoolCountController.h"
#import "SINACircularBeadUtils.h"
#import "SINAStuApproveSelectSchoolViewController.h"
#import "SINAStuApproveSchoolClassViewController.h"
#import "SINAHttpRequestUtils.h"
#import "SINAStudentTabBarViewController.h"
#import "SINATeacherTabBarViewController.h"
#import "SINAControllerUtils.h"
#import "SINALoginViewController.h"
#import "SINANavLoginViewController.h"
#import "SINAControllerUtils.h"
#import "SINAIdentitySelectViewController.h"

@interface SINAStuApproveSchoolCountController ()
//学号
@property(strong,nonatomic) UITextField *studentSchoolCountUILabel;
@property(strong,nonatomic) UITextField *studentSchoolCountPasswordUILabel;
@end

@implementation SINAStuApproveSchoolCountController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super initBackItem];
    SINAUserModel *userModel = [[SINACommonUserHelper share] getUserModel];
    if (userModel!=nil) {
        if ([userModel.identitys integerValue]==1) {
            self.navigationItem.title=@"学生认证";
        } else {
            self.navigationItem.title=@"老师认证";
        }
    } else {
        self.navigationItem.title=@"学生认证";
    }
    [self initViewFunction];
}
-(void) initViewFunction{
    UIScrollView *mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, mainW, mainH-49)];
    mainScrollView.contentSize=CGSizeMake(mainW, mainH+10);
    [self.view addSubview:mainScrollView];
    [self.view setBackgroundColor:[UIColor colorWithHexString:@"#eeeeee"]];
    
    UIView *itemView1 =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 22, mainW, 48)];
    [itemView1 setBackgroundColor:[UIColor whiteColor]];
    [mainScrollView addSubview:itemView1];
    
    
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetHeight(itemView1.frame)/2-10, mainW-30, 21)];
    titleLabel.text=@"学号";
    [titleLabel setFont:[UIFont systemFontOfSize:16]];
    titleLabel.textColor=[UIColor colorWithHexString:@"#212121"];
    
    [itemView1 addSubview:titleLabel];
    
    UITextField *inputTextField = [[UITextField alloc]initWithFrame:CGRectMake(55, CGRectGetHeight(itemView1.frame)/2-17, mainW-45, 36)];
    
    [inputTextField setFont:[UIFont systemFontOfSize:16]];
    inputTextField.placeholder=@"请输入学号";
    inputTextField.textColor=[UIColor colorWithHexString:@"#878787"];
    
    self.studentSchoolCountUILabel =inputTextField;
    
    [itemView1 addSubview:inputTextField];
    
    //
    UIView *itemView2 =[[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(itemView1.frame)+22, mainW, 48)];
    [itemView2 setBackgroundColor:[UIColor whiteColor]];
    [mainScrollView addSubview:itemView2];
    
    
    
    UILabel *titleLabel2 = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetHeight(itemView2.frame)/2-10, mainW-30, 21)];
    titleLabel2.text=@"密码";
    [titleLabel2 setFont:[UIFont systemFontOfSize:16]];
    titleLabel2.textColor=[UIColor colorWithHexString:@"#212121"];
    
    [itemView2 addSubview:titleLabel2];
    
    UITextField *inputTextField2 = [[UITextField alloc]initWithFrame:CGRectMake(55, CGRectGetHeight(itemView2.frame)/2-17, mainW-45, 36)];
    
    [inputTextField2 setFont:[UIFont systemFontOfSize:16]];
    inputTextField2.placeholder=@"请输入学号密码";
    inputTextField2.textColor=[UIColor colorWithHexString:@"#878787"];
    
    self.studentSchoolCountPasswordUILabel =inputTextField2;
    
    [itemView2 addSubview:inputTextField2];
    
    
    
    UILabel *nextLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(itemView2.frame)+48, mainW-30, 42)];
    nextLabel.text=@"下一步";
    nextLabel.textAlignment=NSTextAlignmentCenter;
    [nextLabel setFont:[UIFont systemFontOfSize:20]];
    nextLabel.textColor=[UIColor colorWithHexString:@"#ffffff"];
    [SINACircularBeadUtils makeCircularBead:1 andView:nextLabel andIsSetBackground:YES];
    [mainScrollView addSubview:nextLabel];
    
    WeakSelf;
    //下一步
    [[SINAUiviewClickLiserner alloc]viewClickFunction:nextLabel andWithBlick:^(UIView *view) {
        [weakSelf nextFunction];
    }];
    //选择学校
    [[SINAUiviewClickLiserner alloc]viewClickFunction:itemView1 andWithBlick:^(UIView *view) {
        if ([self.navigationItem.title isEqualToString:@"学生认证"]) {
            return ;
        }
        SINAStuApproveSelectSchoolViewController *studentController=[[SINAStuApproveSelectSchoolViewController alloc]init];
        studentController.currentSchooleModel = weakSelf.currentSchooleModel;
        [weakSelf.navigationController pushViewController:studentController animated:YES];
    }];
    
    
    SINAUserModel *userModel = [[SINACommonUserHelper share] getUserModel];
    if (userModel!=nil) {
        if ([userModel.identitys integerValue]==1) {
            
        } else {
            titleLabel.text=@"证书";
            inputTextField2.placeholder=@"请输入证书密码";
            inputTextField.placeholder=@"请输入证书编号";
        }
    } else {
        
    }
}
-(void) nextFunction{
    [self.view endEditing:YES];
    
    NSString *studentCount = self.studentSchoolCountUILabel.text;
    NSString *msgStudent = @"请输入你的学号";
    SINAUserModel *userModel = [[SINACommonUserHelper share] getUserModel];
    if ([userModel.identitys integerValue]==1) {
        msgStudent = @"请输入你的学号";
    }else{
        msgStudent = @"请输入你的证书编号";
    }
    if (studentCount==nil||studentCount.length<1) {
        
        WISAlertView *alertView =
        [[WISAlertView alloc]initWithTitle:@"提示" message:msgStudent sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
        
        return;
    }
    NSString *password = self.studentSchoolCountPasswordUILabel.text;
    NSString *msgPassword = @"请输入你的学号";
    
    if ([userModel.identitys integerValue]==1) {
        msgPassword = @"请输入你的学号密码";
    }else{
        msgPassword = @"请输入你的证书密码";
    }
    if (password==nil||password.length<1) {
        
        WISAlertView *alertView =
        [[WISAlertView alloc]initWithTitle:@"提示" message:msgPassword sureBtn:@"确定" cancleBtn:nil];
        [alertView showXLAlertView];
        
        return;
    }
    
    
    if (userModel==nil||userModel.userUid==nil||[userModel.userUid isEqualToString:@""]) {
        NSString *message =@"用户信息异常 请重新登录";
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:@"取消"];
        [alertView showXLAlertView];
        WeakSelf;
        alertView.resultIndex = ^(NSInteger index) {
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        };
        return;
    }
    //认证请求参数
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //身份标识 1 学生； 2 老师 String identifity
    if ([userModel.identitys integerValue]==1) {
        
        [dict setObject:[NSString stringWithFormat:@"%@",@"1"] forKey:@"identifity"];
    }else{
        
        [dict setObject:[NSString stringWithFormat:@"%@",@"2"] forKey:@"identifity"];
    }
    
    //真实姓名String realname
    [dict setObject:self.studentName forKey:@"realname"];
    //学校id String universityid
    [dict setObject:[NSString stringWithFormat:@"%@",self.currentSchooleModel.schoolId] forKey:@"universityid"];
    //院id String collegeid
    if ([self.selectSchoolCollegeModel.tid integerValue]!=0) {
        [dict setObject:[NSString stringWithFormat:@"%@",self.selectSchoolCollegeModel.tid] forKey:@"collegeid"];
    }
    if ([self.selectDepartMentModel.tid integerValue]!=0) {
        //系id String collsystemid
        [dict setObject:[NSString stringWithFormat:@"%@",self.selectDepartMentModel.tid] forKey:@"collsystemid"];
    }
    //专业id    String majorid
    if ([self.selectSpecialtyModel.tid integerValue]!=0) {
        [dict setObject:[NSString stringWithFormat:@"%@",self.selectSpecialtyModel.tid] forKey:@"majorid"];
    }
    if ([self.selectSchoolClassModel.tid integerValue]!=0) {
        //班级id String classifyid
        [dict setObject:[NSString stringWithFormat:@"%@",self.selectSchoolClassModel.tid] forKey:@"classifyid"];
    }
    if ([self.selectSchoolYearModel.tid integerValue]!=0) {
        //入学年份 String schoolyear
        [dict setObject:[NSString stringWithFormat:@"%@",self.selectSchoolYearModel.tid] forKey:@"schoolyear"];
    }
    //学号 String number
    [dict setObject:[NSString stringWithFormat:@"%@",studentCount] forKey:@"number"];
    //青果登录密码 String loginpassword
    [dict setObject:[NSString stringWithFormat:@"%@",password] forKey:@"loginpassword"];
    //用户的uuid String uuid
    [dict setObject:userModel.userUid forKey:@"uuid"];
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
  
    [self startLoading];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userApproveUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            //            NSDictionary *result = responseData[@"content"];
            
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"认证成功" sureBtn:@"刷新用户信息" cancleBtn:nil];
            alertView.resultIndex = ^(NSInteger index) {
                ////用户身份标识  1学生  2教师 -1没有选择身份
                //home页面
//                if ([userModel.identitys isEqualToString:@"1"]) {
//                    SINAStudentTabBarViewController *tabBarViewController = [[SINAStudentTabBarViewController alloc]init];
//                    [[SINAControllerUtils alloc]restoreRootViewController:tabBarViewController andWithWindow:weakSelf.view.window];
//                } else {
//                    SINATeacherTabBarViewController *tabBarViewController = [[SINATeacherTabBarViewController alloc]init];
//                    [[SINAControllerUtils alloc]restoreRootViewController:tabBarViewController andWithWindow:weakSelf.view.window];
//                }
               
    
                if ([[SINACommonUserHelper share]getUserModel].userPassword!=nil) {
                     [self reLoginUpdateInformationFunction];
                } else {
                     [self updateFailesFunction];
                }
            };
            
            [alertView showXLAlertView];
            
            
            
        }else if ([code isEqualToString:@"1003"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"验证失败" message:@"请核对你所选的信息" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }else if ([code isEqualToString:@"1006"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"验证失败" message:@"请核对你所选的信息" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }else if ([code isEqualToString:@"1010"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"已绑定过" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {

        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"认证验证失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)viewWillAppear:(BOOL)animated{
    
}

-(void)reLoginUpdateInformationFunction{
  
    [self startLoading];
    SINAUserModel *preUserModel = [[SINACommonUserHelper share]getUserModel];
    //登录请求参数
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //1.学生phone
    [dict setObject:preUserModel.userPhone forKey:@"phone"];
    //    NSString *passwordSign = [SINAMd5Utils md5:userPassword];
    
    //2.未加密密码
    [dict setObject:preUserModel.userPassword forKey:@"passwords"];
    
    
    //获取系统时间戳
    NSDate* date1 = [NSDate date];
    NSTimeInterval time1 =[date1 timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f",time1];
    DLog(@"系统时间戳:%@",timeString);
    
    //3.签名时间 当前时间
    [dict setObject:timeString forKey:@"signtimes"];
    //4.唯一标识符
    NSString *uuid = [NSUUID UUID].UUIDString;
    [dict setObject:uuid forKey:@"signuid"];
    
    //5.签名
    NSString *signflag = [SINAMd5Utils md5:[NSString stringWithFormat:@"%@%@",uuid,timeString]];
    [dict setObject:signflag forKey:@"signflag"];
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
   
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userLoginUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
         NSDictionary *result = responseData[@"content"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
            SINAUserModel *userModel=[SINAUserModel userWithDict:result];
            SINACommonUserHelper *userHelper=[SINACommonUserHelper share];
            userModel.userPassword =preUserModel.userPassword;
            [userHelper saveUserModel:userModel];
            
            
            if (userModel.userUid==nil||[userModel.userUid isEqualToString:@""]) {
                //登录页面
                SINALoginViewController *rootViewControll = [[SINALoginViewController alloc]init ];
                SINANavLoginViewController *homeController = [[SINANavLoginViewController alloc] initWithRootViewController:rootViewControll];
                [self restoreRootViewController:homeController];
                
            } else {
                if (userModel.identitys==nil||[userModel.identitys isEqualToString:@"-1"]) {
                    SINAIdentitySelectViewController *selectControll = [[SINAIdentitySelectViewController alloc]initWithNibName:@"SINAIdentitySelectViewController" bundle:nil];
                    [self.navigationController pushViewController:selectControll animated:YES];
                }else{
                    ////用户身份标识  1学生  2教师 -1没有选择身份
                    //home页面
                    if ([userModel.identitys isEqualToString:@"1"]) {
                        SINAStudentTabBarViewController *tabBarViewController = [[SINAStudentTabBarViewController alloc]init];
                        [self restoreRootViewController:tabBarViewController];
                    } else {
                        SINATeacherTabBarViewController *tabBarViewController = [[SINATeacherTabBarViewController alloc]init];
                        [self restoreRootViewController:tabBarViewController];
                    }
                }
            }
        }else if ([code isEqualToString:@"1003"]) {
            [weakSelf stopLoading];
            [self updateFailesFunction];
        }else{
            [weakSelf stopLoading];
            [self updateFailesFunction];
        }
    } failure:^(NSError *error, NSInteger errCode) {
        [weakSelf stopLoading];
        
        //重新登录
        [self updateFailesFunction];
    }];
}
-(void) updateFailesFunction{
    
    NSString *message =@"更新用户信息失败 请重新登录";
    WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
    alertView.resultIndex = ^(NSInteger index) {
        [self toLogin];
    };
    [alertView showXLAlertView];
}
-(void) toLogin{
    //重新登录
    SINALoginViewController *rootViewControll = [[SINALoginViewController alloc]init ];
    SINANavLoginViewController *homeController = [[SINANavLoginViewController alloc] initWithRootViewController:rootViewControll];
    [[SINAControllerUtils alloc]restoreRootViewController:homeController andWithWindow:self.view.window];
}
- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = self.view.window;
    
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        window.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}

@end
